package cn.bellychang.leetcode.question637;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * @author ChangLiang
 * @date 2021/2/8
 */
public class Solution {

    public List<Double> averageOfLevels(TreeNode root) {

        List<Double> list = new ArrayList<>();

        Deque<TreeNode> queue = new ArrayDeque<>();

        queue.push(root);
        int currLevelSize = queue.size();
        int nextLevelSize = 0;
        double sum = 0;
        int tempSize = 0;
        while (currLevelSize != 0) {
            TreeNode poll = queue.poll();
            sum += poll.val;
            tempSize++;
            if (poll.left != null) {
                queue.offer(poll.left);
                nextLevelSize++;
            }
            if (poll.right != null) {
                queue.offer(poll.right);
                nextLevelSize++;
            }
            if (tempSize == currLevelSize) {
                currLevelSize = nextLevelSize;
                nextLevelSize = 0;
                list.add(sum / tempSize);
                sum = 0;
                tempSize = 0;
            }
        }
        return list;
    }
}
